package cn.funeralobjects.youtube.dl.extension.model;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils;

import java.util.Objects;


/**
 * @author FuneralObjects
 * Create date: 2020/4/3 4:07 PM
 */
@Data
@Accessors(chain = true)
public class DownloadTask {
    /**
     * 视频id
     */
    private String id;
    /**
     * 下载的format参数
     */
    private String format;
    /**
     * 标题
     */
    private String title;
    /**
     * 开始时间
     */
    private Long startTime;
    /**
     * 使用代理
     */
    private String proxy = "";

    /**
     * 任务结束时间
     */
    private Long endTime = 0L;

    private static final Integer LENGTH = 5;
    public static String[] convertRowData(DownloadTask task){
        if(isInvalidData(task)){
            throw new RuntimeException("Exists data of the task is invalid!");
        }
        return new String[]{
                task.id,
                task.format,
                task.title,
                String.valueOf(task.startTime),
                task.proxy,
                String.valueOf(task.endTime)
        };
    }

    public static DownloadTask convertTask(String[] rowData){
        if(rowData == null || rowData.length < LENGTH){
            throw new RuntimeException("Exists data convert to task is invalid!");
        }
        return new DownloadTask()
                .setId(rowData[0])
                .setFormat(rowData[1])
                .setTitle(rowData[2])
                .setStartTime(Long.valueOf(rowData[3]))
                .setProxy(rowData[4])
                .setEndTime(Long.valueOf(rowData[5]));
    }

    public static boolean isInvalidData(DownloadTask task){
        return task == null
                || StringUtils.isEmpty(task.getId())
                || StringUtils.isEmpty(task.getTitle())
                || StringUtils.isEmpty(task.getFormat())
                || task.getStartTime() == null;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {return true;}
        if (o == null || getClass() != o.getClass()) {return false;}
        DownloadTask that = (DownloadTask) o;
        return getId().equals(that.getId()) &&
                getFormat().equals(that.getFormat());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getId(), getFormat());
    }
}
